<?php

namespace app\common\model\xilumarket;

use app\common\library\Auth;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Model;
use think\model\Pivot;
use traits\model\SoftDelete;
use function fast\array_get;

class OrderAppeal extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'xilumarket_order_appeal';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'images_text',
        'createtime_text',
    ];

    public function getImagesTextAttr($value,$data){
        $images = [];
        $value = isset($data['images'])?$data['images']:'';
        if($value && is_string($value)){
            $images_array = explode(',',$value);
            foreach ($images_array as $image){
                $images[] = cdnurl($image,true);
            }
        }
        return $images;
    }

    public function getCreatetimeTextAttr($value,$data){
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y.m.d H:i", $value) : $value;
    }

    /**
     * 申诉提交
     */
    public static function add($params,$user){
        $validator = new \app\common\validate\xilumarket\OrderAppeal();
        if(!$validator->check($params)){
            throw new Exception($validator->getError());
        }
        $order_id = array_get($params,'order_id');
        $order_product_id = array_get($params,'order_product_id');
        $appeal = self::where('order_id',$order_id)
            ->where('order_product_id',$order_product_id)
            ->find();
        if($appeal){
            throw new Exception("已有申诉");
        }
        $order = Order::get($order_id);
        if(in_array($order->refund_status,[1,2])){
            throw new Exception("商品已退款或在申请中");
        }
        $params['images'] = $params['images'] ? (is_array($params['images']) ? implode(',',$params['images']) : $params['images']) :'';
        $params['state'] = '1';
        $params['user_id'] = $user->id;
        Db::startTrans();
        try {
            #订单商品的售后状态更改
            $appeal = self::create($params);
            // 增加售后单变动记录
            AftersaleLog::operate_add($order, null, $user, 'user', [
                'title' => '买家平台申诉',
                'description' => '买家已向平台申请退款申诉',
                'images' =>  $params['images']
            ]);
        }catch (Exception|PDOException $e){
            Db::rollback();
            throw $e;
        }
        Db::commit();
        return $appeal;

    }
}
